#ifndef THREADPOOL_H
#define THREADPOOL_H

#include <iostream>
#include <list>
#include <exception>
#include <pthread.h>
#include <../MultiThreadProgramming/locker.hpp>

template<typename T>
class threadPool {
public:
    threadPool(int threadNumber = 8, int maxRequests = 10000);
    ~threadPool();
    bool append(T& request);

private:
    static void* worker(void* arg);
    void run();

private:
    int m_thread_number;
    int m_max_request;
    pthread_t* m_threads;
    std::list<T*> m_workqueue;
    locker m_queuelocker;
    sem m_queuestat;
    bool m_stop;
}

template <typename T>
threadPool<T>::threadPool(int threadNumber, int maxRequests)
:   m_thread_number(threadNumber), m_max_request(maxRequests),
    m_stop(false), m_threads(nullptr)
{
    if(thread <= 0 || maxRequests <= 0) {
        throw std::exception();
    }

    m_threads = new pthread_t[m_thread_number];
    if(!m_threads) {
        throw std::exception();
    }

    for(int i = 0; i < m_thread_number; ++i) {
        cout << "create the " << i << "th thread" << endl;
        if(pthread_create(m_threads + i, nullptr, worker, this) != 0) {
            delete[] m_threads;
            throw std::exception();
        } 
        if(pthread_detach(m_threads[i])) {
            delete[] m_threads;
            throw std::exception();
        }
    }
}
template <typename T>
threadPool<T>::~threadPool() {
    delete[] m_threads;
    m_stop = true;
}

template <typename T>
bool threadPool<T>::append(T* request) {
    m_queuelocker.lock();
    if(m_workqueue.size() > m_max_request) {
        m_queuelocker.unlock();
        return false;
    }
    m_workqueue.push_back(request);
    m_queuelocker.unlock();
    m_queuestat.post();
    return true;
}

template <typename T>
void* threadPool<T>::worker(void* arg) {
    threadPool* pool = (threadPool*)arg;
    pool->run();
    return pool;
}

template <typename T>
void threadPool<T>::run() {
    while(!m_stop) {
        m_queuestat.wait();
        m_queuelocker.lock();
        if(m_workqueue.empty()) {
            m_queuelocker.unlock();
            continue;
        }
        T* request = m_workqueue.front();
        m_workqueue.pop_front();
        m_queuelocker.unlock();
        if(!request) {
            continue;
        }
        request->process();
    }
}

#enfif // THREADPOOL_H